import os
from flask import Flask,render_template
from flask_uploads import UploadSet,IMAGES,configure_uploads,patch_request_class
from flask_wtf import FlaskForm #pip install flask_wtf
#导入表单上传字段及验证器
from flask_wtf.file import FileAllowed,FileRequired,FileField
#导入表单提交按钮 验证器
from wtforms import SubmitField
from flask_bootstrap import Bootstrap
from PIL import Image
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') or '12qwaszx34erdfcv'
#配置上传大小
app.config['MAX_CONTENT_LENGTH'] = 1024*1024*8

#配置上传的位置
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd()


bootstrap = Bootstrap(app)
#创建上传对象
photos = UploadSet('photos',IMAGES)
configure_uploads(app,photos)
patch_request_class(app,size=None) #默认64M 如果size为None 那么就按照MAX_CONTENT_LENGTH 配置的大小 8m

class UploadForm(FlaskForm):
    photo = FileField('头像上传',validators=[FileRequired('文件没有被选择'),FileAllowed(photos,message="只能上传图片")])
    submit = SubmitField("上传")

#生成随机的字符串
def random_string(length=20):
    import random
    base_str = 'qwertyuiopasdfghjklzxcvbnm0123456789'
    return ''.join(random.choice(base_str) for i in range(length))


@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/upload/',methods=['GET','POST'])
def upload():
    img_url = None
    form = UploadForm()
    if form.validate_on_submit():#判断是否符合表单的要求
        #获取文件后缀
        suffix = os.path.splitext(form.photo.data.filename)[-1]
        #拼接新的文件名
        filename = random_string() +suffix
        #保存文件
        photos.save(form.photo.data,name=filename) #保存为新的文件名
        #生成缩略图 告诉从哪里打开上传的图片
        pathname= os.path.join(app.config['UPLOADED_PHOTOS_DEST'],filename)

        #打开文件
        img = Image.open(pathname)
        #设置尺寸
        img.thumbnail((128,128))
        #保存文件
        img.save(pathname)

        #save()保存后的文件名字
        #获取图片的url
        img_url = photos.url(filename)
    return render_template('index.html',img_url=img_url,form=form)

if __name__ == '__main__':
    app.run()
